<script setup lang="ts">
import { ref, computed, h, onMounted } from 'vue'
import {
  NDataTable,
  NButton,
  NIcon,
  NModal,
  NInput,
  NSpace,
  NForm,
  NFormItem,
  NTag
} from 'naive-ui'
import { Code, Plus, Settings, Trash } from '@vicons/tabler'
import { fetchShortcuts, addShortcut, updateShortcut, deleteShortcut } from '@/service/api/build'

interface Shortcut {
  id: number
  name: string
  command: string
  description: string
}

const shortcuts = ref<Shortcut[]>([])
const showModal = ref(false)
const currentShortcut = ref<Shortcut | null>(null)
const formRef = ref(null)

const loadShortcuts = async () => {
  try {
    const response = await fetchShortcuts()
    shortcuts.value = response.data
  } catch (error) {
    console.error('Failed to load shortcuts:', error)
  }
}

const handleAddShortcut = () => {
  currentShortcut.value = {
    id: 0,
    name: '',
    command: '',
    description: ''
  }
  showModal.value = true
}

const saveShortcut = async () => {
  formRef.value?.validate(async (errors: any) => {
    if (!errors && currentShortcut.value) {
      try {
        if (currentShortcut.value.id === 0) {
          await addShortcut({
            name: currentShortcut.value.name,
            command: currentShortcut.value.command,
            description: currentShortcut.value.description
          })
        } else {
          await updateShortcut(currentShortcut.value)
        }
        await loadShortcuts()
        showModal.value = false
        currentShortcut.value = null
      } catch (error) {
        console.error('Failed to save shortcut:', error)
      }
    }
  })
}

const editShortcut = (shortcut: Shortcut) => {
  currentShortcut.value = JSON.parse(JSON.stringify(shortcut))
  showModal.value = true
}

const removeShortcut = async (id: number) => {
  try {
    await deleteShortcut(id)
    await loadShortcuts()
  } catch (error) {
    console.error('Failed to delete shortcut:', error)
  }
}

const rules = {
  name: {
    required: true,
    trigger: ['input', 'blur'],
    message: '名称不能为空'
  },
  command: {
    required: true,
    trigger: ['input', 'blur'],
    message: '命令不能为空'
  },
  description: {
    required: true,
    trigger: ['input', 'blur'],
    message: '描述不能为空'
  }
}

const columns = [
  {
    title: '名称',
    key: 'name',
    render: (row: Shortcut) => {
      return h(NInput, {
        value: row.name,
        size: 'small',
        onUpdateValue: (value) => (row.name = value)
      })
    }
  },
  {
    title: '命令',
    key: 'command',
    render: (row: Shortcut) => {
      return h(NInput, {
        value: row.command,
        size: 'small',
        onUpdateValue: (value) => (row.command = value)
      })
    }
  },
  {
    title: '描述',
    key: 'description',
    render: (row: Shortcut) => {
      return h(NInput, {
        value: row.description,
        size: 'small',
        onUpdateValue: (value) => (row.description = value)
      })
    }
  },
  {
    title: '操作',
    key: 'actions',
    align: 'center',
    width: 80,
    render: (row: Shortcut) => {
      return h(
        'div',
        {
          size: 'small',
          class: 'w-full justify-center flex gap-2 items-center'
        },
        [
          h(NButton, { text: true, size: 'small', onClick: () => editShortcut(row) }, () =>
            h(NIcon, { component: Settings, size: 18, color: '#868e96' })
          ),
          h(NButton, { text: true, size: 'small', onClick: () => removeShortcut(row.id) }, () =>
            h(NIcon, { component: Trash, size: 18, color: '#f03e3e' })
          )
        ]
      )
    }
  }
]

// 初始加载快捷指令
onMounted(() => {
  loadShortcuts()
})
</script>
<template>
  <div class="w-full p-4 rounded-lg bg-#F9F9F9">
    <div class="flex items-center justify-between mb-4">
      <div class="flex items-center">
        <n-icon size="20" :component="Code" color="#2970FF" />
        <span class="ml-2 text-lg font-medium mr-1">快捷指令</span>
        <CustomTooltip content="用户在输入框中输入 / 即可唤起快捷指令,如: 继续,一步步思考, 等专业通用词汇"  placement="right"/>
      </div>
      <n-button quaternary @click="handleAddShortcut" size="small" class="rounded-lg">
        <template #icon>
          <n-icon size="13"><Plus /></n-icon>
        </template>
        添加
      </n-button>
    </div>
    <div class="mb-4 text-#787878 text-sm text-center" v-if="shortcuts.length === 0">
      用户在输入框中输入 / 即可唤起快捷指令,如: 继续,一步步思考, 等专业通用词汇
    </div>
    <div class="w-full h-full p-4" v-else>
      <n-data-table :columns="columns" :data="shortcuts" style="border-radius: 15px" size="small">
      </n-data-table>
    </div>
  </div>

  <n-modal
    v-model:show="showModal"
    居中显示
    :style="{ width: '460px', top: 'calc(50% - 200px)' }"
    preset="card"
    title="编辑快捷指令"
    :mask-closable="false"
    class="rounded-2xl"
  >
    <n-form
      v-if="currentShortcut"
      :model="currentShortcut"
      label-placement="top"
      label-width="auto"
      require-mark-placement="right-hanging"
      :rules="rules"
      ref="formRef"
    >
      <n-form-item label="名称" path="name">
        <n-input v-model:value="currentShortcut.name" placeholder="请输入名称" />
      </n-form-item>
      <n-form-item label="命令" path="command">
        <n-input v-model:value="currentShortcut.command" placeholder="请输入命令" />
      </n-form-item>
      <n-form-item label="描述" path="description">
        <n-input v-model:value="currentShortcut.description" placeholder="请输入描述" />
      </n-form-item>
    </n-form>
    <template #footer>
      <div class="flex justify-end">
        <n-button @click="showModal = false">取消</n-button>
        <n-button type="primary" class="ml-2" @click="saveShortcut">保存</n-button>
      </div>
    </template>
  </n-modal>
</template>

<style scoped lang="scss">
.cursor-move {
  cursor: move;
}
::v-deep(.n-data-table-wrapper) {
  border-radius: 15px;
}
</style>
